package com.qf.web.servlet;

import cn.dsna.util.images.ValidateCode;
import com.qf.pojo.Address;
import com.qf.pojo.User;
import com.qf.service.AddressService;
import com.qf.service.UserService;
import com.qf.service.impl.AddressServiceImpl;
import com.qf.service.impl.UserServiceImpl;
import com.qf.utils.Base64Utils;
import com.qf.utils.StrUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author 千锋教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
@WebServlet("/userservlet")
public class UserServlet extends BaseServlet {


    UserService userService = new UserServiceImpl();

    /**
     * 退出功能
     *  1. 清除session
     *  2. 清除cookie
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public String logOut(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //清除session
        request.getSession().removeAttribute("user");

        request.getSession().invalidate();

        //清除cookie
        Cookie cookie = new Cookie("userinfo-2202", Base64Utils.encode(""));
        //生存时间
        cookie.setMaxAge(1);
        cookie.setPath("/"); //在此网站任意路径可用
        response.addCookie(cookie);

        return  "redirect:/login.jsp";

    }
        //登录
    public String login(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //判空
        if(StrUtils.isEmpty(username) || StrUtils.isEmpty(password)) {
            return "redirect:/login.jsp";
        }

        User user = userService.login(username, password);
        if(user != null) {
            //把用户信息存储到session中
            request.getSession().setAttribute("user", user);
            String auto = request.getParameter("auto");
            if("on".equalsIgnoreCase(auto)) {
                String userinfo = username +  "#" + password;
                //把用户信息存储到cookie
                Cookie cookie = new Cookie("userinfo-2202", Base64Utils.encode(userinfo));
                //生存时间
                cookie.setMaxAge(14 * 24 * 60 * 60);
                cookie.setPath("/"); //在此网站任意路径可用
                response.addCookie(cookie);
            }
            return "redirect:/index.jsp";
        } else {
            return "redirect:/login.jsp";
        }
    }

        //验证 验证码的正确与否
    public void checkCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取用户输入的验证码 ，判断是否为空
        String code1 = request.getParameter("code");
        if(StrUtils.isEmpty(code1)) {
            response.getWriter().print("1");
            return;
        }

        String code2 = (String) request.getSession().getAttribute("code");

        if(code1.equalsIgnoreCase(code2)) {
            response.getWriter().print("0");
        }else {
            response.getWriter().print("1");
        }



    }

    //GUI: 图形化
    public void code(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //创建验证码
        ValidateCode validateCode = new ValidateCode(100, 35, 2, 10);
        //把验证码存储到session
        request.getSession().setAttribute("code", validateCode.getCode());
        //输出验证码 到 响应流
        validateCode.write(response.getOutputStream());
    }


    /**
     * 注册
     * @param request
     * @param response
     * @return
     */
    public String register(HttpServletRequest request, HttpServletResponse response) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String gender = request.getParameter("gender");
        //如果数据为null， 跳转 register.jsp
        if(StrUtils.isEmpty(username) || StrUtils.isEmpty(email) || StrUtils.isEmpty(password)) {
            return "redirect:/register.jsp";
        }

        //检测用户名是否存在
        boolean flag = userService.checkUsername(username);
        if(flag) {
            return "redirect:/register.jsp";
        }


        //调用业务层，注册用户, 如果注册成功，跳转到登录页面，如果注册失败，跳转到注册页面
        boolean isSuccess = userService.register(username, password, email, gender);
        if(isSuccess){
            return "redirect:/login.jsp";
        } else {
            return "redirect:/register.jsp";
        }
    }

    /**
     * 检测用户名是否存在
     * @param request
     * @param response
     * @throws IOException
     */
    public void checkUserName(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取username
        String username = request.getParameter("username");
        //判断是否为空
        if(StrUtils.isEmpty(username)){
            response.getWriter().print("0");
        } else {

            //发起校验（数据库）, 如果存在返回true， 不存在返回false
            boolean flag = userService.checkUsername(username);
            if(flag) {
                response.getWriter().print("1");
            }else {
                response.getWriter().print("2");
            }
        }



    }
    AddressService addressService = new AddressServiceImpl();
    //获取地址列表页面
    public String getAddress(HttpServletRequest request, HttpServletResponse response) throws Exception {

        User user = (User) request.getSession().getAttribute("user");

        List<Address> addList = addressService.findAddListByUid(user.getId());

        request.setAttribute("addList", addList);

        return "forward:/self_info.jsp";
    }

    //删除地址
    public String deleteAddress(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取 地址id
        String id = request.getParameter("id");
        addressService.deleteById(id);

        return "redirect:/userservlet?method=getAddress";
    }

    //获取地址列表页面
    public String addAddress(HttpServletRequest request, HttpServletResponse response) throws Exception {
        User user = (User) request.getSession().getAttribute("user");
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String detail = request.getParameter("detail");
        //如果为空
        if(StrUtils.isEmpty(name ) || StrUtils.isEmpty(phone) || StrUtils.isEmpty(detail)) {
            System.out.println("数据有误，请重新添加");
            return "redirect:/userservlet?method=getAddress";
        }

        Address address = new Address();
        address.setDetail(detail);
        address.setLevel(0);
        address.setName(name);
        address.setPhone(phone);
        address.setUid(user.getId());

        addressService.insert(address);

        return "redirect:/userservlet?method=getAddress";
    }

    /**
     * 设置默认收货地址
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public String defaultAddress(HttpServletRequest request, HttpServletResponse response) throws Exception {
        User user = (User) request.getSession().getAttribute("user");
        String aid = request.getParameter("id");

        addressService.setDefaultAddress(aid, user.getId());

        return "redirect:/userservlet?method=getAddress";
    }

    //获取地址列表页面
    public String updateAddress(HttpServletRequest request, HttpServletResponse response) throws Exception {
        User user = (User) request.getSession().getAttribute("user");
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String detail = request.getParameter("detail");
        int level = Integer.parseInt(request.getParameter("level"));
        int id = Integer.parseInt(request.getParameter("id"));
        //如果为空
        if(StrUtils.isEmpty(name ) || StrUtils.isEmpty(phone) || StrUtils.isEmpty(detail)) {
            System.out.println("数据有误，请重新添加");
            return "redirect:/userservlet?method=getAddress";
        }

        Address address = new Address();
        address.setDetail(detail);
        address.setLevel(level);
        address.setName(name);
        address.setPhone(phone);
        address.setUid(user.getId());
        address.setId(id);

        addressService.update(address);

        return "redirect:/userservlet?method=getAddress";
    }
}
